package org.example.com.editor.command.workspaceCommand;

import org.example.com.editor.command.Command;
import org.example.com.editor.exception.UnSavedModificationException;
import org.example.com.editor.logger.LogManager;
import org.example.com.editor.ui.ConsoleUI;
import org.example.com.editor.workspace.Workspace;

import java.io.IOException;
import java.util.Scanner;

public class CloseCommand implements Command {
    private final LogManager logManager;

    public CloseCommand(LogManager logManager) {
        this.logManager = logManager;
    }


    @Override
    public void execute(Workspace workspace, ConsoleUI ui) {
        Scanner scanner = ui.getScanner();
        String[] args = ui.getCommandArgs();

        // 1. 参数校验（Command 层职责）
        if (args.length > 2) {
            ui.printError("用法：close [文件路径]");
            return;
        }

        String filePath = (args.length == 1) ? workspace.getActiveFile() : args[1];


        try{
            workspace.closeFile(filePath,false);
            logManager.onCommandExecuted(filePath, args);
            ui.printInfo("文件已关闭：" + filePath);
        }
        catch(UnSavedModificationException e){
            ui.printError(e.getMessage());
            while(true){
                try {
                    String choice = scanner.nextLine();
                    if(choice.equals("y")){
                        workspace.saveFile(filePath);
                        ui.printInfo("已保存文件：" + filePath);
                        workspace.closeFile(filePath,false);
                        break;
                    }else if(choice.equals("n")){
                        workspace.closeFile(filePath,true);
                        ui.printInfo("未保存文件，直接关闭：" + filePath);
                        break;
                    }else{
                        ui.printError("无法识别的选项,请重新输入");
                    }
                } catch (IOException ex) {
                    ui.printError("保存文件时发生IO异常：" + ex.getMessage());
                }
            }
        }
        catch (IllegalArgumentException e){
            ui.printError(e.getMessage());
        }catch (IOException e){
            ui.printError("关闭文件时发生IO异常：" + e.getMessage());
        }

    }

    @Override
    public String getName() {
        return "close";
    }
}